<template>
    <div class="calc">
        <h2 class="text-center">{{ $t('home.calc') }}</h2>
        <div class="flex-start-center home-profit">
            <div class="flex-start-center home-profit-item">
                <div>
                    <div class="flex-start-center home-profit-title">
                        <img src="@/assets/images/upbit.svg">
                        <span>Upbit</span>
                    </div>
                    <div class="text-primary fz14 mt10">
                        ￦{{ thousandSeparate(upbitData?.krw) }}
                    </div>
                    <div class="text-subtitle fz12">
                        ${{ thousandSeparate(precision(upbitData?.usdt)) }}
                    </div>
                </div>
            </div>
            <div class="flex-start-center home-profit-item">
                <div>
                    <div class="flex-start-center home-profit-title">
                        <img src="@/assets/images/binance.svg">
                        <span>Binance</span>
                    </div>
                    <div class="text-primary fz14 mt10">
                        ￦{{ thousandSeparate(precision(binanceData?.krw, 0)) }}
                    </div>
                    <div class="text-subtitle fz12">
                        ${{ thousandSeparate(precision(binanceData?.usdt)) }}
                    </div>
                </div>
            </div>
            <div class="flex-start-center home-profit-item">
                <div>
                    <div class="flex-start-center home-profit-title">
                        <span>Kimchi</span>
                    </div>
                    <div class="text-primary fz14 mt10">
                        {{ precision(diffData.rate) }}%
                    </div>
                    <div class="text-subtitle fz12">
                        ￦{{ thousandSeparate(precision(diffData.krw, 0)) }}
                    </div>
                </div>
            </div>
        </div>
        <div class="mt10">
            <el-select
                v-model="coin"
                style="width: 100%;"
                size="large"
                filterable
            >
                <el-option
                    v-for="item in currencies"
                    :key="item.currency"
                    :label="`${$locale.value === 'ko-kr' ? item.korean_name : item.english_name}(${item.currency})`"
                    :value="item.currency"
                />
            </el-select>
        </div>
        <div class="flex-start-center mt10">
            <el-radio-group
                v-model="rateRadio"
                @change="rateRadioChange"
            >
                <el-radio
                    :value="true"
                    size="large"
                >
                    {{ $t('home.auto') }}
                </el-radio>
                <el-radio
                    :value="false"
                    size="large"
                >
                    {{ $t('home.manual') }}
                </el-radio>
            </el-radio-group>
            <div
                v-if="assetsNum"
                class="flex-start-center ml20 lh40 fz20 text-primary"
            >
                ￦{{ thousandSeparate(precision(diffData?.krw * assetsNum, 0)) }}
            </div>
        </div>
        <div class="flex-start-center">
            <div
                v-if="rateRadio"
                class="flex-start-center lh40 fz14 "
            >
                <span>Rate: </span>
                <span class="ml10 flex-start-center">
                    <span>￦{{ thousandSeparate(precision(krwRate)) }}</span>
                    <span class="fz10">(USD)</span>
                </span>
                <span class="ml10 flex-start-center">
                    <span>￦{{ thousandSeparate(precision(usdtRate, 0)) }}</span>
                    <span class="fz10">(USDT)</span>
                </span>
            </div>
            <div
                v-else
            >
                <el-input
                    v-model="krwRateInput"
                    :oninput="replaceNumber"
                    placeholder="Please enter krw price"
                    size="large"
                />
            </div>
            <div class="ml10">
                <el-input
                    v-model="assetsNum"
                    :oninput="replaceNumber"
                    placeholder="Please enter the asset quantity"
                    size="large"
                />
            </div>
        </div>

        <div>
            <el-button
                type="primary"
                @click="scan"
            >
                Scan
            </el-button>
        </div>

        <div class="calc-img">
            <a
                href="https://share.bitget.com/u/JTB6CBYL?clacCode=4UCDLUJU"
                class="flex-start-center"
                target="_blank"
            >
                <img src="@/assets/images/bitget-en.png">
            </a>
        </div>
    </div>
</template>

<script setup>
import { getCurrencyList } from '@/utils/api';
import types from '@/store/types';
import { thousandSeparate, precision } from '@/utils/tools';

const {
    dispatch, state, getters, commit,
} = useStore();
const coin = ref('BTC');
const currencies = ref([]);
const rateRadio = ref(true);
const krwRateInput = ref('');
const krwRateList = computed(() => getters.krwRateList);
const upbitData = computed(() => state.ws.upbitData);
const binanceData = computed(() => state.ws.binanceData);
const usdtRate = computed(() => state.ws.usdtRate);
const krwRate = computed(() => {
    if (rateRadio.value || !krwRateInput.value) {
        return state.ws.usdRate;
    }

    return Number(krwRateInput.value);
});
const assetsNum = ref('1');
const diffData = computed(() => {
    if (rateRadio.value || !krwRateInput.value) {
        return getters.diffData;
    }

    if (upbitData.value && binanceData.value) {
        const usdt = (upbitData.value.krw / krwRate.value) - binanceData.value.usdt;
        const krw = upbitData.value.krw - (binanceData.value.usdt * krwRate.value);
        const rate = (usdt / binanceData.value.usdt) * 100;

        return {
            usdt,
            krw,
            rate,
        };
    }

    return {};
});

const getCurrency = async () => {
    const res = await getCurrencyList();
    const { code, data } = res;
    if (code === 200 && data) {
        currencies.value = data;
    }
};

const replaceNumber = (el) => {
    let { value } = el.target;
    const max = 2;
    const reg2 = new RegExp(`^(\\-)*(\\d+)\\.(\\d{0,${max}}).*$`);
    value = value.replace(/[^0-9.]/g, '').replace(/\.{2,}/g, '.').replace(reg2, '$1$2.$3');
    el.target.value = value;
};

const rateRadioChange = (val) => {
    if (!val) {
        krwRateInput.value = precision(krwRateList.value?.[0]?.rate, 2);
    }
};

watch(coin, async (val, old) => {
    if (old) {
        const res = await dispatch(types.UN_SUB_TICKER, old);

        if (res) {
            commit(types.SET_COIN, val);
            dispatch(types.SUB_TICKER);
        }
    }
});

const scan = () => {
    const { WebApp } = window?.Telegram || {};
    if (WebApp) {
        WebApp.showScanQrPopup('Scan', (val) => {
            WebApp.showPopup({
                title: 'Scan Result',
                message: val,
                buttons: [
                    { type: 'close' },
                ],
            });

            return true;
        });
    }
};

onMounted(async () => {
    coin.value = state.ws.coin;
    await getCurrency();
    await dispatch(types.GET_KRW_RATE);
    await dispatch(types.SET_TIMEOUT_RATE);
    dispatch(types.INIT_WS);
});
</script>

<style lang="scss" scoped>
.calc {
    padding: 20px;
}

.home-profit {
    gap: 10px;
    margin-top: 10px;

    .home-profit-item {
        flex: 1;
        border-radius: 5px;
        padding: 10px;
        transition: all 0.3s ease;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.175);

        .home-profit-rate {
            height: 40px;
            font-size: 14px;
        }

        .home-profit-asset {
            height: 40px;
            font-size: 18px;
        }

        .home-profit-title {
            gap: 10px;

            img {
                width: 20px;
                height: 20px;
            }

            span {
                font-size: 16px;
                line-height: 20px;
            }
        }
    }
}

.calc-img {
    margin-top: 10px;

    img {
        max-width: 100%;
    }
}
</style>
